package com.org.manhu.chargehelper.download;

import java.io.File;

import android.content.Context;
import android.os.AsyncTask;

/**
 * @文件名：DownLoadTask.java
 * @包名：com.example.downloaddemo.downloader
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年3月3日 下午12:01:46
 *
 * @描述：
 */
public class DownloadTask extends AsyncTask<String, Integer, String> {
	private Downloader mmDownloader = null;

	private int mmFileSize = -1;
	private Context mContext;
	private String downUrl;

	private UpdateListener listener = null;

	private String downPath;

	public DownloadTask(Context context) {
		this.mContext = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected String doInBackground(String... params) {
		downPath = params[1];
		downUrl = params[0];
		mmDownloader = new Downloader(mContext, params[0], new File(params[1]),
				5);
		mmFileSize = mmDownloader.getFileSize();
		DownloadListener downloadListener = new DownloadListener() {
			@Override
			public void onDownloadSize(int size) {
				publishProgress(size);
			}
		};
		try {
			mmDownloader.download(downloadListener);
			return "下载成功";
		} catch (Exception e) {
			e.printStackTrace();
			if (listener != null) {
				listener.onError(e.toString());
			}
		}
		return null;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		float percent = (float) values[0] / mmFileSize * 100;
		if (listener != null) {
			listener.updateProgress((int) percent);
		}
	}

	public void pause() {
		if (mmDownloader != null) {
			mmDownloader.stop();
			cancel(true);
		}
	}

	public void cancleTask() {
		if (mmDownloader != null) {
			mmDownloader.cancle();
			cancel(true);
			if (listener != null) {
				listener.onCancle();
			}
		}
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if (result != null) {
			if (listener != null) {
				listener.onComplete(downPath + getFileName(downUrl));
			}
		}
	}

	/** 设置更新监听 **/
	public void setUpdateListener(UpdateListener listener) {
		this.listener = listener;
	}

	/**
	 * 获取文件名
	 * 
	 * @param path
	 *            文件路径
	 * @return 文件名称
	 */
	private String getFileName(String path) {
		return new File(path).getName();
	}
}
